<template>
  <div class="patrol-route-container">
    <div class="patrol-header">
      <h2>巡更路线</h2>
      <el-select
          v-model="selectedCommunity"
          placeholder="选择小区"
          @change="loadRoutes"
          style="width: 200px; margin-right: 10px;"
      >
        <el-option
            v-for="community in communityList"
            :key="community.id"
            :label="community.name"
            :value="community.id"
        ></el-option>
      </el-select>
      <el-button type="primary" @click="handleAddRoute">
        <Plus /> 添加路线
      </el-button>
    </div>

    <el-table
        :data="routes"
        border
        style="width: 100%;"
        v-loading="loading"
    >
      <el-table-column prop="routeName" label="路线名称" width="150" />
      <el-table-column prop="communityName" label="所属社区" width="150" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="包含点位" width="200">
        <template #default="scope">
          <span v-if="scope.row.points.length > 0">
            {{ scope.row.points.slice(0, 3).map(p => p.pointName).join(',') }}
            {{ scope.row.points.length > 3 ? '...' : '' }}
          </span>
          <span v-else>无点位</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button
              size="small"
              type="primary"
              @click="editRoute(scope.row)"
              style="margin-right: 5px;"
          >
            编辑
          </el-button>
          <el-button size="small" type="danger" @click="deleteRoute(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑路线弹窗 -->
    <el-dialog
        title="巡更路线信息"
        v-model="dialogVisible"
        width="700px"
    >
      <el-form
          :model="formData"
          ref="formRef"
          label-width="120px"
          :rules="formRules"
      >
        <el-form-item label="路线名称" prop="routeName">
          <el-input v-model="formData.routeName" />
        </el-form-item>
        <el-form-item label="所属社区" prop="communityId">
          <el-select v-model="formData.communityId" placeholder="请选择社区">
            <el-option
                v-for="community in communityList"
                :key="community.id"
                :label="community.name"
                :value="community.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
              v-model="formData.status"
              active-value="1"
              inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
          ></el-switch>
        </el-form-item>
        <el-form-item label="路线描述" prop="description">
          <el-input type="textarea" v-model="formData.description" :rows="3" />
        </el-form-item>
        <el-form-item label="路线点位" prop="pointIds">
          <el-select
              v-model="formData.pointIds"
              multiple
              filterable
              remote
              reserve-keyword
              placeholder="请选择点位"
              :remote-method="remoteMethod"
              :loading="pointLoading"
              collapse-tags
          >
            <el-option
                v-for="point in pointOptions"
                :key="point.pointId"
                :label="point.pointName"
                :value="point.pointId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="点位排序">
          <div class="sortable-container">
            <el-card
                v-for="(pointId, index) in formData.pointIds"
                :key="pointId"
                class="sortable-item"
                shadow="hover"
            >
              {{ getPointName(pointId) || '未知点位' }}
              <div class="sort-handle" @click="movePoint(index, -1)">
                <ArrowUp />
              </div>
              <div class="sort-handle" @click="movePoint(index, 1)">
                <ArrowDown />
              </div>
            </el-card>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveRoute">保存</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import {
  getRouteByCommunity,
  addRoute,
  updateRoute,
  deleteRoute as deleteRouteApi
} from '../api/patrolRoute'
import {getPointByCommunity, getPointByCommunityWithQuery} from '../api/patrolPoint'
import { watch } from 'vue'

export default {
  name: 'PatrolRoute',
  components: {
    Plus,
    ArrowUp,
    ArrowDown
  },
  setup() {
    // 社区列表
    const communityList = ref([
      { id: 1, name: '万象城' },
      { id: 2, name: '万达文旅城' },
      { id: 3, name: '碧桂园' }
    ])

    // 点位选项
    const pointOptions = ref([])
    const pointLoading = ref(false)

    // 响应式数据
    const dialogVisible = ref(false)
    const selectedCommunity = ref(1)
    const routes = ref([])
    const loading = ref(false)

    const isEdit = ref(false)
    const formRef = ref(null)

    // 表单数据
    const formData = reactive({
      routeId: null,
      routeName: '',
      communityId: null,
      status: '1',
      description: '',
      pointIds: []
    })

    // 点位缓存（用于显示点位名称）
    const pointMap = ref(new Map())

    // 表单验证规则
    const formRules = reactive({
      routeName: [
        { required: true, message: '请输入路线名称', trigger: 'blur' }
      ],
      communityId: [
        { required: true, message: '请选择所属社区', trigger: 'change' }
      ],
      pointIds: [
        { required: true, message: '请至少选择一个点位', trigger: 'change' }
      ]
    })

    // 根据ID获取点位名称
    const getPointName = (pointId) => {
      return pointMap.value.get(pointId)?.pointName || ''
    }

    // 加载路线数据
    const loadRoutes = async () => {
      try {
        loading.value = true
        let {data:data} = await getRouteByCommunity(selectedCommunity.value)
        console.log("后端返回的路线数据：", data) // 打印数据确认是否有 points 字段

        if (data.code === 0) {
          // 关键修复：为每个路线添加 points 字段（若不存在则设为空数组）
          routes.value = data.data.map(route => ({
            ...route,
            points: route.points || [] // 确保 points 始终是数组（空数组或实际数据）
          }))

          // 构建点位缓存（同时兼容 points 为空的情况）
          const newPointMap = new Map()
          routes.value.forEach(route => {
            // 遍历前先判断 points 是否存在（避免报错）
            (route.points || []).forEach(point => {
              newPointMap.set(point.pointId, point)
            })
          })
          pointMap.value = newPointMap
        } else {
          ElMessage.error(data.message || '加载路线失败')
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试')
        console.error('加载路线失败:', error)
      } finally {
        loading.value = false
      }
    }

    // 远程搜索点位
    const remoteMethod = async (query) => {
      if (!query) {
        pointOptions.value = []
        return
      }

      try {
        pointLoading.value = true;
        // 修正参数传递方式：直接在URL参数中传递query
        let {data:data} = await getPointByCommunityWithQuery(selectedCommunity.value, query);
        if (data.code === 0) {
          pointOptions.value = data.data;
        } else {
          ElMessage.error(data.message || '搜索点位失败');
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试');
        console.error('搜索点位失败:', error);
      } finally {
        pointLoading.value = false;
      }
    };

    // 移动点位顺序
    const movePoint = (index, direction) => {
      if (direction === -1 && index > 0) {
        // 上移
        [formData.pointIds[index], formData.pointIds[index - 1]] =
            [formData.pointIds[index - 1], formData.pointIds[index]]
      } else if (direction === 1 && index < formData.pointIds.length - 1) {
        // 下移
        [formData.pointIds[index], formData.pointIds[index + 1]] =
            [formData.pointIds[index + 1], formData.pointIds[index]]
      }
    }

    // 添加路线
    const handleAddRoute = () => {
      console.log('添加路线按钮被点击');
      dialogVisible.value = true
      isEdit.value = false
      formData.routeId = null
      formData.routeName = ''
      formData.communityId = selectedCommunity.value
      formData.status = '1'
      formData.description = ''
      formData.pointIds = []

      // 加载点位选项
      remoteMethod('')
    }

    // 编辑路线
    const editRoute = (row) => {
      console.log('编辑路线按钮被点击', row);
      isEdit.value = true
      formData.routeId = row.routeId
      formData.routeName = row.routeName
      formData.communityId = row.communityId
      formData.status = row.status.toString()
      formData.description = row.description
      formData.pointIds = row.points.map(p => p.pointId)
      dialogVisible.value = true

      // 加载点位选项
      remoteMethod('')
    }

    // 删除路线
    const deleteRoute = async (row) => {
      try {
        await ElMessageBox.confirm(
            `确定要删除路线 "${row.routeName}" 吗？`,
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
        )

        const res = await deleteRouteApi(row.routeId)
        if (res.code === 200) {
          ElMessage.success('删除成功')
          await loadRoutes()
        } else {
          ElMessage.error(res.message || '删除失败')
        }
      } catch (error) {
        // 如果是取消操作，不显示错误信息
        if (error !== 'cancel') {
          ElMessage.error('网络错误，请稍后重试')
          console.error('删除失败:', error)
        }
      }
    }

    // 保存路线
    const saveRoute = async () => {
      // 关键修复：使用async/await处理表单验证的异步逻辑
      try {
        // 表单验证（Element Plus的validate方法返回Promise）
        await formRef.value.validate();

        // 准备提交数据
        const submitData = {
          route: {
            routeId: formData.routeId,
            routeName: formData.routeName,
            communityId: formData.communityId,
            status: parseInt(formData.status),
            description: formData.description,
            isDelete: 1, // 默认为未删除
            createTime: new Date().toISOString(),
            updateTime: new Date().toISOString()
          },
          pointIds: formData.pointIds
        }

        const saveMethod = isEdit.value ? updateRoute : addRoute
        const actionName = isEdit.value ? '更新' : '添加';
        // 调用API（修正响应解析方式）
        let {data:data} = await saveMethod(submitData);
        if (data.code === 0) { // 后端返回的成功码是0，不是200
          ElMessage.success(`${actionName}成功`);
          dialogVisible.value = false;
          await loadRoutes(); // 刷新列表
        } else {
          ElMessage.error(data.message || `${actionName}失败`);
        }
      } catch (error) {
        // 表单验证失败时的处理
        if (error.name === 'Error') {
          ElMessage.error('表单验证失败，请检查输入');
        } else {
          ElMessage.error('网络错误，请稍后重试');
          console.error(`${actionName}失败:`, error);
        }
      }
    };
    watch(
        () => dialogVisible.value,
        (newVal) => {
          console.log('dialogVisible 值变为:', newVal)
        }
    )
    // 组件挂载时加载数据
    onMounted(() => {
      loadRoutes()
    })

    return {
      communityList,
      selectedCommunity,
      routes,
      loading,
      dialogVisible,
      formData,
      formRules,
      formRef,
      pointOptions,
      pointLoading,
      getPointName,
      loadRoutes,
      remoteMethod,
      movePoint,
      handleAddRoute,
      editRoute,
      deleteRoute,
      saveRoute
    }
  }
}
</script>

<style scoped>
.patrol-route-container {
  padding: 20px;
}

.patrol-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.sortable-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.sortable-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  min-width: 150px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.sort-handle {
  cursor: pointer;
  margin-left: 10px;
  color: #909399;
}

.sort-handle:hover {
  color: #409eff;
}
</style>